package com.audaque.springboot.foshanupload.redis.component;

import com.audaque.springboot.foshanupload.redis.component.iface.RedisLuaBucketRateLimterIface;
import com.audaque.springboot.foshanupload.core.exception.RetryMaxException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author zgb
 * @desc ...
 * @date 2022-02-28 16:45:00
 */
@Slf4j
@Component
public class LuaBucketRateLimterAsyncSender {


    @Autowired
    private AsyncSender asyncSender;


    public void send(RedisLuaBucketRateLimterIface redisLuaBucketRateLimterIface, String name, String id, String productCountKey, String consumeCountKey,int availableProcessorsQueueSize,Integer waitConsumeInQueueSize) throws Exception {
        log.debug("开始发送-同步抢令牌："+id);
        //获取令牌：控制消息生产速率，重试直到成功
        try {
            redisLuaBucketRateLimterIface.run();
        } catch (Exception e) {
            log.error("获取令牌-异常栈:" + e);
            throw e;
        }
        log.debug("id:" + id + "获取到令牌");
        //发送任务
        this.retryUntilSuccess(  name,  id,  productCountKey,  consumeCountKey, availableProcessorsQueueSize, waitConsumeInQueueSize);
    }

    private  void retryUntilSuccess( String name, String id, String productCountKey, String consumeCountKey,int availableProcessorsQueueSize,Integer waitConsumeInQueueSize){
        try {
            log.debug("开始发送-异步发送："+id);
            asyncSender.send(  name,id, productCountKey, consumeCountKey, availableProcessorsQueueSize, waitConsumeInQueueSize);
        } catch (RetryMaxException e) {
            log.debug("等待上报办结结束,重试次数达到上限，继续重试");
            retryUntilSuccess(  name,  id,  productCountKey,  consumeCountKey, availableProcessorsQueueSize, waitConsumeInQueueSize);
        }
    }
}
